{% extends "base.html" %}
{% import "_my_wtf_macros.html" as my_wtf_macros %}

{% block title %}万屏时代报价工具--新增产品{% endblock %}

{% block panel_heading %}万屏时代报价工具--新增产品{% endblock %}

{% block panel_body %}
    <form id="add-product-form" action="{{ url_for('product_bp.add_product') }}"
          method="post" class="form" role="form" onsubmit="on_form_submit()">

        {{ form.hidden_tag() }}

        {{ my_wtf_macros.form_field(form.product_type_id, div_col=6, label_col=3, field_col=9) }}
        <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>

        {{ my_wtf_macros.form_field(form.brand_id, div_col=6, label_col=3, field_col=9) }}
        {{ my_wtf_macros.form_field(form.brand_model_id, div_col=6, label_col=3, field_col=9) }}
        <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>

        {{ my_wtf_macros.form_field(form.price, div_col=6, label_col=3, field_col=9) }}
        {{ my_wtf_macros.form_field(form.suggest_price, div_col=6, label_col=3, field_col=9) }}
        <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>

        {{ my_wtf_macros.form_field(form.source, div_col=6, label_col=3, field_col=9) }}
        {{ my_wtf_macros.form_field(form.weight, div_col=6, label_col=3, field_col=9) }}
        <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>
        <div class="well well-sm">
            产品图片
            <div class="pull-right btn-group">
                <a href="#" id="add-product-pictures"
                   class="btn btn-xs btn-success"
                   style="margin-right: 5px;" target="_self">
                    添加图片
                </a>
            </div>
        </div>
        <div class="container form-group">
            <ul id="picture-container">
                {% for each in form_pictures %}
                    <li class="pull-left"
                        style="position:relative; margin-top: 10px; margin-right: 10px;list-style:none; border:1px solid #DDD">
                        <i class="glyphicon glyphicon-remove text-red remove-image-btn"
                           aria-hidden="true"
                           style="position: absolute; right: 5px; top:3px;"
                           onclick="remove_picture(this)"
                        ></i>

                        <img src="{{ each }}" data-url="{{ each }}"
                             class="picture-url"
                             style="width: 150px; height: 150px">
                    </li>
                {% endfor %}
            </ul>
        </div>
        <br>

        <div id="product_params_container">
        </div>
        <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>


        <div id="product_specs_container">
        </div>

        <div class="pull-right">
            <button type="submit" class="btn btn-success"
                    id="add-demand-btn">
                新增
            </button>
        </div>

    </form>

    <form action="" id="picture-file-form">
        <input class="form-control" type="file" style="display:none"
               id="image_file"
               name="image_file" value=""
               accept=".jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.BMG,.PNG"
        >
    </form>

{% endblock %}


{% block scripts %}
    {{ super() }}
    <script>
        function remove_picture(obj) {
            $(obj).parent().remove();
        }

        function on_form_submit() {
            add_params();
            add_pictures();
            add_specs();
        }

        function add_pictures() {
            var pictures = [];
            $('.picture-url').each(function () {
                pictures.push($(this).data('url'));
            });
            $('#pictures').val(JSON.stringify(pictures));
        }

        function add_params() {
            var params = [];
            $('.param_input').each(function () {
                var spec = {};
                spec.technology_param_id = $(this).data('id');
                spec.name = $(this).data('name');
                spec.value = $(this).val();
                spec.unit = $(this).data('unit');
                spec.calculate_item = $(this).data('calculate_item');
                spec.is_display = $(this).data('is_display');
                spec.is_required = $(this).data('is_required');
                spec.value_type = $(this).data('value_type');
                spec.display_rule = $(this).data('display_rule');
                spec.options = $(this).data('options');
                spec.parent_id = $(this).data('parent_id');
                spec.tag_type = $(this).data('tag_type');
                spec.placeholder = $(this).data('placeholder');
                params.push(spec);
            });
            $('#params').val(JSON.stringify(params));
        }

        function add_specs() {
            var specs = [];
            $('.spec_input').each(function () {
                var spec = $(this).data('spec_json');
                spec.values = $(this).val();
                specs.push(spec);
            });
            $('#specs').val(JSON.stringify(specs));
        }
        // 通过产品类型获取技术参数
        function get_specs_by_type() {
            var product_type_id = $("#product_type_id").val();
            $.ajax({
                url: "{{ url_for('product_bp.ajax_spec_choices')}}?product_type_id=" + product_type_id,
                cache: true
            }).done(function (data) {
                var container = $("#product_specs_container");
                container.html('');
                if (data.length) {
                    container.append('<div class="well well-sm">产品规格</div>')
                }
                for (var i in data) {
                    var item = data[i];
                    var spec_json = JSON.stringify(item);
                    var option_text = '';
                    if (!item['is_input_type'] && item['options']) {
                        option_text = '  选项: ' + JSON.stringify(item.options);
                    }
                    var spec_label = item.name + option_text;

                    container.append('<div class="form-group col-xs-6 "> ' +
                        '<div class="row"> <label class="control-label  col-xs-3" ' +
                        'for="param_name"> 规格名</label> <div class="col-xs-9"> ' +
                        '<input class="form-control" id="spec_name" name="spec_name" ' +
                        'type="text" disabled=true value=\'' + spec_label +
                        '\'> </div> </div>');

                    container.append('<div class="form-group col-xs-6 "> ' +
                        '<div class="row"> <label class="control-label  col-xs-3" ' +
                        'for="spec_value">' + '规格值（' + item.unit_display + '）</label> <div class="col-xs-9"> ' +
                        '<input class="form-control spec_input" id="spec_value"' +
                        ' name="spec_value" type="text" value=""' + ' data-spec_json=\'' + spec_json +
                        '\'> </div> </div>');

                }

            }).fail(function () {
                alert("获取产品规格失败，请联系系统管理员!")
            });
        }

        // 通过产品类型获取技术参数
        function get_params_by_type() {
            var product_type_id = $("#product_type_id").val();
            $.ajax({
                url: "{{ url_for('product_bp.ajax_params')}}?product_type_id=" + product_type_id,
                cache: true
            }).done(function (data) {
                var container = $("#product_params_container");
                container.html('');
                if (data.length) {
                    container.append('<div class="well well-sm">技术参数</div>')
                }
                for (var i in data) {
                    var item = data[i];
                    var title_display = '';
                    if(item.is_display){
                        title_display = '(标题)'
                    }
                    var required_display = '';
                    if(item.is_required){
                        required_display = 'required'
                    }
                    container.append('<div class="form-group col-xs-6 "> ' +
                        '<div class="row"> <label class="control-label  col-xs-3" ' +
                        'for="param_name"> 技术参数名'+ title_display + '</label> <div class="col-xs-9"> ' +
                        '<input class="form-control" id="param_name" name="param_name" type="text" disabled=true value=' + item.name +
                        '> </div> </div>');

                    container.append('<div class="form-group col-xs-6 ' + required_display +
                        '"><div class="row"> <label class="control-label  col-xs-3" ' +
                        'for="spec_value">' + '技术参数值（' + item.unit_display + '）</label> <div class="col-xs-9"> ' +
                        '<input class="form-control param_input" id="spec_value"' +
                        ' name="spec_value" type="text" value=' + item.default + ' data-id='
                        + item.id + ' data-unit=' + item.unit + ' data-name=' + item.name + ' data-calculate_item=' + item.calculate_item +
                        ' data-is_display=' + item.is_display +
                        '> </div> </div>');
                }

            }).fail(function () {
                alert("获取产品规格失败，请联系系统管理员!")
            });
        }

        function get_brands_by_type() {
            var product_type_id = $('#product_type_id').val();
            $.ajax({
                url: "{{ url_for('product_bp.ajax_brand_choices')}}",
                data: JSON.stringify({
                    'product_type_id': product_type_id
                }),
                type: 'post',
                dataType: 'json',
                contentType: 'application/json',
                cache: true
            }).done(function (data) {
                $("#brand_id").empty();
                for (var i = 0; i < data.length; i++) {
                    var id = data[i][0];
                    var name = data[i][1];
                    $("#brand_id").append(
                        "<option value='" + id + "'>" + name + "</option>"
                    );
                }

            }).fail(function () {
                $(obj).data('content', '服务器错误');
                $(obj).popover('show');
            });
        }

        function get_models_by_brand() {
            var brand_id = $('#brand_id').val();
            $.ajax({
                url: "{{ url_for('product_bp.ajax_brand_model_choices')}}",
                data: JSON.stringify({
                    'brand_id': brand_id
                }),
                type: 'post',
                dataType: 'json',
                contentType: 'application/json',
                cache: true
            }).done(function (data) {
                $("#brand_model_id").empty();
                for (var i = 0; i < data.length; i++) {
                    var id = data[i][0];
                    var name = data[i][1];
                    $("#brand_model_id").append(
                        "<option value='" + id + "'>" + name + "</option>"
                    );
                }

            }).fail(function () {
                $(obj).data('content', '服务器错误');
                $(obj).popover('show');
            });
        }

        $('#add-product-pictures').click(function () {
            $('#image_file').click();
        });

        $('#image_file').change(function () {
            var form = new FormData(document.getElementById("picture-file-form"));
            var container = $("#picture-container");
            $.ajax({
                url: "{{ url_for('product_bp.ajax_upload_picture') }}",
                data: form,
                type: 'post',
                accept: 'application/json',
                processData: false,
                contentType: false,
                success: function (data) {
                    if (!data.status) {
                        container.append(
                            '<li class="pull-left" style="position:relative; margin-top: 10px; margin-right: 10px;list-style:none; border:1px solid #DDD">' +
                            '<i class="glyphicon glyphicon-remove text-red"' +
                            'aria-hidden="true" style="position: absolute; right: 5px; top:3px;" onclick="remove_picture(this)"></i> <img class="picture-url" src="' +
                            data.url + '" data-url="' + data.url + '" style="width: 150px; height: 150px"> </li>'
                        );
                        $('#image_file').empty();
                    }
                    else {
                        console.log('文件不能为空');
                    }

                }
            })
        });

        $(document).ready(function () {
            $("#product_type_id").change(function () {
                get_brands_by_type();
                get_params_by_type();
                get_specs_by_type();
                $("#brand_model_id").empty();
                $("#brand_model_id").append(
                    "<option value='" + 0 + "'>" + "--请选择型号--" + "</option>"
                );
            });
            var product_type_id = $("#product_type_id").val();
            if (product_type_id != 0) {
                get_brands_by_type();
                get_params_by_type();
                get_specs_by_type();
            };

            $("#brand_id").change(function () {
                get_models_by_brand();
            });
            var brand_id = $("#brand_id").val();
            if (brand_id != 0) {
                get_models_by_brand();
            }
        })
    </script>

{% endblock %}
